package com.atguigu.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.bean.TrafficHomeDetailPageViewBean;
import com.atguigu.edu.realtime.util.ClickhouseUtil;
import com.atguigu.edu.realtime.util.DateFormatUtil;
import com.atguigu.edu.realtime.util.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Date;

public class DwsTrafficHomeDetailPageViewWindow {
    //1  获取数据流
    //2  筛选出主页和详情页的访问
    //3  转换成统计类型，主页的ct值 和 详情页的ct值 要根据状态进行判断
    //4  开窗聚合
    //5  写入clickhouse
    public static void main(String[] args) throws Exception {
        //0 环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);
        //1  获取数据流
        String sourceTopic="dwd_traffic_page_log";
        String groupId="dws_traffic_home_detail_window";
        DataStreamSource<String> kafkaStream = env.addSource(MyKafkaUtil.getKafkaConsumer(sourceTopic, groupId));
        SingleOutputStreamOperator<JSONObject> jsonObjStream = kafkaStream.map(JSON::parseObject);
        //2  筛选出主页和详情页的访问
        SingleOutputStreamOperator<JSONObject> filteredStream = jsonObjStream.filter(new FilterFunction<JSONObject>() {
            @Override
            public boolean filter(JSONObject jsonObject) throws Exception {
                JSONObject pageObj = jsonObject.getJSONObject("page");
                if (pageObj.getString("page_id").equals("home") || pageObj.getString("page_id").equals("good_detail")) {
                    return true;
                }
                return false;
            }
        });

        KeyedStream<JSONObject, String> midKeyedStream = filteredStream.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));

        //3  转换成统计类型，主页的ct值 和 详情页的ct值 要根据状态进行判断
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> homeDetailStream = midKeyedStream.process(new KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>() {

            ValueStateDescriptor<String> homeLastVisitStateDescr = new ValueStateDescriptor<>("home_last_visit", String.class);
            ValueStateDescriptor<String> detailLastVisitStateDescr = new ValueStateDescriptor<>("detail_last_visit", String.class);

            ValueState<String> homeLastVisitState = null;
            ValueState<String> detailLastVisitState = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                //创建状态 2个状态  1首页最后一次访问日期  2 详情页最后一次访问日期
                homeLastVisitStateDescr.enableTimeToLive(StateTtlConfig.newBuilder(org.apache.flink.api.common.time.Time.days(1)).build());
                detailLastVisitStateDescr.enableTimeToLive(StateTtlConfig.newBuilder(org.apache.flink.api.common.time.Time.days(1)).build());

                homeLastVisitState = getRuntimeContext().getState(homeLastVisitStateDescr);
                detailLastVisitState = getRuntimeContext().getState(detailLastVisitStateDescr);
            }

            @Override
            public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>.Context ctx, Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                Long ts = jsonObject.getLong("ts");
                String curDt = DateFormatUtil.toDate(ts);
                Long homeUvCt = 0L;
                Long detailUvCt = 0L;
                //1 首页判断
                if(jsonObject.getJSONObject("page").getString("page_id").equals("home")){

                    //有状态  以前来过   --> 是不是今天 是今天来过  不计次数  不是今天 -->计次数
                    // 无状态  -->计次数
                    String homeLastVisitDt = homeLastVisitState.value();
                    if (homeLastVisitDt == null || !homeLastVisitDt.equals(curDt)) {// 没有状态或者有状态但是不是今天的 记一次访问
                        homeUvCt = 1L;
                        homeLastVisitState.update(curDt);
                    }
                }else{
                    //2 详情页判断
                    //有状态  以前来过   --> 是不是今天 是今天来过  不计次数  不是今天 -->计次数
                    // 无状态  -->计次数
                    String detailLastVisitDt = detailLastVisitState.value();
                    if (detailLastVisitDt == null || !detailLastVisitDt.equals(curDt)) {// 没有状态或者有状态但是不是今天的 记一次访问
                        detailUvCt = 1L;
                        detailLastVisitState.update(curDt);
                    }
                }
                // 只要有一个为1的情况才保留,否则的丢弃
                if (detailUvCt == 1L || homeUvCt == 1L) {
                    out.collect(new TrafficHomeDetailPageViewBean("", "", homeUvCt, detailUvCt, ts));
                }
            }
        });

     //   homeDetailStream.print();
        //4  开窗聚合
        //4.1 水位线
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> homeDetailWmStream = homeDetailStream.assignTimestampsAndWatermarks(WatermarkStrategy.<TrafficHomeDetailPageViewBean>forBoundedOutOfOrderness(Duration.ofMillis(1000))
                .withTimestampAssigner(new SerializableTimestampAssigner<TrafficHomeDetailPageViewBean>() {
                    @Override
                    public long extractTimestamp(TrafficHomeDetailPageViewBean element, long recordTimestamp) {
                        return element.getTs();
                    }
                })
        );
        //4.2
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> reduceStream = homeDetailWmStream.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                    @Override
                    public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean bean1, TrafficHomeDetailPageViewBean bean2) throws Exception {
                        bean1.setHomeUvCt(bean1.getHomeUvCt() + bean2.getHomeUvCt());
                        bean1.setGoodDetailUvCt(bean1.getGoodDetailUvCt() + bean2.getGoodDetailUvCt());
                        return bean1;
                    }
                }, new AllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<TrafficHomeDetailPageViewBean> beanItr, Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                        //补充 窗口起始结束事件  ts
                        for (TrafficHomeDetailPageViewBean trafficHomeDetailPageViewBean : beanItr) {
                            trafficHomeDetailPageViewBean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                            trafficHomeDetailPageViewBean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                            trafficHomeDetailPageViewBean.setTs(new Date().getTime());
                            out.collect(trafficHomeDetailPageViewBean);
                        }
                    }
                });

         reduceStream.print();
        //5  写入clickhouse
//        reduceStream.addSink(ClickhouseUtil.getSink(
//                "insert into  dws_traffic_home_detail_page_view_window  values(?,?,?,?,?)"
//
//        ));
        env.execute();
    }
}
